package com.hxn.wxshake.web;

import com.alibaba.fastjson.JSONObject;
import com.hxn.wxshake.bean.Data;
import com.hxn.wxshake.bean.WXCallBack;
import com.hxn.wxshake.bean.WXSendUserInfo;
import com.hxn.wxshake.cache.ConcurrentHashMapTest;
import com.hxn.wxshake.utils.RedisUtils;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @ClassName OAuthController
 * @Description TODO
 * @Author hxn
 * @Date 2019/7/31 15:41
 * @Version 1.0
 **/
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OAuthController {


    @Value("${justauth.type.WECHAT.client-id}")
    private String appid;
    @Value("${justauth.type.WECHAT.redirect-uri}")
    private String redirectUri;
    @Value("${myhttp}")
    private String myhttp;


    private final AuthRequestFactory factory;
    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/login/wechat")
    public void login(HttpServletResponse response) throws IOException {
        final String responseType = "code",scope="snsapi_userinfo",state="STATE",connectRedirect="1";
        WXSendUserInfo wxSendUserInfo = new WXSendUserInfo(appid,redirectUri,responseType,scope,state,connectRedirect);
        response.sendRedirect(wxSendUserInfo.getSendUserInfoUrl());
    }

    @RequestMapping("/wechat/callback")
    public void login(AuthCallback callback,HttpServletResponse httpResponse)throws IOException  {
        AuthRequest authRequest = factory.get(AuthSource.WECHAT);
        AuthResponse response = authRequest.login(callback);
        // 移除校验通过的state
        AuthState.delete(AuthSource.WECHAT);
        //获取微信登录响应的信息
        if(response.getCode() == WXCallBack.SUCCESS){
            WXCallBack wxCallBack = WXCallBack.getByObject(response.getData());
            redisUtils.hPut(IndexAPI.redisName,wxCallBack.getUuid(),new Data().getInitDataString(wxCallBack.getUsername(),wxCallBack.getGender()));
            httpResponse.sendRedirect(wxCallBack.getJumpWXShakePageUrl(myhttp));
        }
    }

}
